package gulimall.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import gulimall.config.ElasticSearchConfig;
import gulimall.constant.EsConstant;
import gulimall.service.ProductSaveService;
import gulimall.to.es.SkuEsModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author HLF
 * @date 2022/6/15 15:16
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource
    private RestHighLevelClient client;

    /**
     * 商品上架(把SkuEsModel对象保存到ElasticSearch中，便于后期检索)
     *
     * @param skuEsModels
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws Exception {
        //将数据批量保存到ElasticSearch中

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());

            ObjectMapper mapper = new ObjectMapper();
            indexRequest.source(mapper.writeValueAsString(skuEsModel), XContentType.JSON);

            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        //保存失败的操作
        boolean hasFailures = bulkResponse.hasFailures();
        if (hasFailures) {
            log.error("商品上架出错");
            return false;
        }
        return true;
    }
}
